import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ApiErrorCode } from '../../common/enums/api-error-code.enum';
import {
  Response,
  ResponseParam,
  CurrentError,
} from '../../common/enums/response';
import { SetOrderInterface } from './order.interface';
import { getRandomInt } from '../../util/utiles';
import { WxApi } from '../../common/wxapi/wxapi.service';
import { imageSync } from 'qr-image';
import { DetailedPeerCertificate } from 'tls';
const moment = require('moment');
import * as NP from 'number-precision';
import { UserService } from '../user/user.service';
import { parse, build } from 'node-xlsx';
import { User } from '../../entities/user.entity';
import { Orders } from '../../entities/order.entity';
import { Goods } from 'src/entities/goods.entity';
import { Device } from 'src/entities/device.entity';

@Injectable()
export class orderService {
  constructor(
    private readonly wxApi: WxApi,
    private readonly userService: UserService,
  ) {}
  @InjectRepository(User) private readonly user: Repository<User>;
  @InjectRepository(Orders) private readonly order: Repository<Orders>;
  @InjectRepository(Goods) private readonly goods: Repository<Goods>;
  @InjectRepository(Device) private readonly device: Repository<Device>;

  /**
   *
   * @description 创建订单
   * @param {number} id
   * @memberof orderService
   */
  public async createOrder(money: number, userId: number, goodsId: number) {
    //消费总金额
    let buyAllMoney: number = money;
    const date: any = new Date();
    //订单号
    const orderCode: string = date.getTime() + getRandomInt(0, 9999);
    //获取用户信息
    const userInfo: User = await this.user.findOneBy({ id: userId });
    const orderInfo: SetOrderInterface = {
      goodsId: goodsId,
      orderCode,
      number: 1,
      userId: userInfo.id,
      head_thumb: userInfo.avatar,
      orderClass: 0,
      userName: userInfo.name,
      userPhone: userInfo.phone,
      money: buyAllMoney,
    };
    try {
      // 添加购买商品订单
      const newOrder: Orders = await this.order.save(orderInfo);
      // 统一下单
      const wxPay: any = await this.wxApi.wxPay(
        orderCode,
        money,
        '127.0.0.1',
        userInfo.openid,
      );
      // await this.SessionKey.setOrderPayment(orderCode,JSON.stringify(wxPay));
      // await this.SessionKey.setTemplateMessage(orderCode,wxPay.prepay_id);
      const data = { price: money, ...wxPay };
      // const data = {price:money};
      let responseParam: ResponseParam = {
        message: ApiErrorCode.LCAK_ORDER_SUCCESS,
        data,
      };
      return Response(responseParam);
    } catch (error) {
      return CurrentError.LACK_PAYORDER_FAIL;
    }
  }

  /** 已发货
   *
   *
   * @param {number} id
   * @returns {Promise<object>}
   * @memberof orderService
   */
  public async setOrderSend(id: number): Promise<object> {
    try {
      await this.order.update({ id }, { orderClass: 2 });
      let responseParam: ResponseParam = {
        message: ApiErrorCode.LACK_SET_SUCCESS,
        data: null,
      };
      return Response(responseParam);
    } catch (error) {
      return CurrentError.LACK_SET_FAIL;
    }
  }

  /** 根据ID获取订单信息
   *
   *
   * @param {number} id
   * @returns {Promise<object>}
   * @memberof orderService
   */
  public async getOrderInfoById(id: number): Promise<object> {
    let orderInfo: any = this.order
      .createQueryBuilder('order')
      .leftJoinAndSelect('order.goods', 'goods')
      .leftJoinAndSelect('order.luck', 'luckgoods')
      .where('order.id=:id', { id })
      .getOne();
    let responseParam: ResponseParam = {
      message: ApiErrorCode.LACK_GET_SUCCESS,
      data: orderInfo,
    };
    return Response(responseParam);
  }

  /** 支付成功回调
   *
   *
   * @param {*} xml
   * @returns
   * @memberof orderService
   */
  public async payNotify(xml: any) {
    const orderInfo: Orders = await this.order.findOneBy({
      orderCode: xml.out_trade_no,
    });
    if (!orderInfo || orderInfo.orderClass != 0) {
      return '';
    }
    await this.order.update({ id: orderInfo.id }, { orderClass: 1 });
    const goodsInfo: Goods = await this.goods.findOneBy({
      id: orderInfo.goodsId,
    });
    const userInfo: User = await this.user.findOneBy({ id: orderInfo.userId });
    if (goodsInfo.isPhone) {
      await this.user.update(
        { id: orderInfo.userId },
        { phoneMoney: userInfo.phoneMoney + orderInfo.money },
      );
    }
    if (goodsInfo.isSms) {
      await this.user.update(
        { id: orderInfo.userId },
        { smsMoney: userInfo.smsMoney + orderInfo.money },
      );
    }
    // if (goodsInfo.isYearVip) {
    //   await this.device.update(
    //     { id: orderInfo.userId },
    //     { expireTime:  },
    //   );
    // }
    return `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
  }

  /** 查询用户已完成订单列表
   *
   *
   * @param {number} page
   * @param {number} pageSize
   * @param {string} openid
   * @returns {Promise<object>}
   * @memberof orderService
   */
  public async orderListByUser(
    page: number,
    pageSize: number,
    openid: string,
  ): Promise<object> {
    const userInfo: User = await this.user.findOneBy({ openid });
    const orderList: Orders[] = await this.order
      .createQueryBuilder('order')
      .leftJoinAndSelect('order.goods', 'goods')
      .where(`order.userId=${userInfo.id}`)
      .andWhere('orderClass !=0')
      .orderBy('order.creatTime', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getMany();
    let responseParam: ResponseParam = {
      message: ApiErrorCode.LACK_GET_SUCCESS,
      data: orderList,
    };
    return Response(responseParam);
  }

  /**
   * 获取订单列表
   *
   * @param {number} page
   * @param {number} pageSize
   * @param {number} orderClass
   * @memberof orderService
   */
  public async getList(
    userInfo: any,
    page: number,
    pageSize: number,
    orderClass?: number,
  ) {
    let orderRep: any = this.order
      .createQueryBuilder('order')
      .leftJoinAndSelect('order.goods', 'goods')
      .where('1');
    if (orderClass) {
      orderRep.andWhere('order.orderClass=:orderClass', { orderClass });
    }
    if (userInfo.role !== 'admin') {
      orderRep.andWhere('order.userId=:userId', { userId: userInfo.userId });
    }
    const orderList: any = await orderRep
      .orderBy('order.creatTime', 'DESC')
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getManyAndCount();
    let responseParam: ResponseParam = {
      message: ApiErrorCode.LACK_GET_SUCCESS,
      data: orderList[0],
      count: orderList[1],
    };
    return Response(responseParam);
  }
}
